import 'package:flutter/material.dart';

class ImageInternalTestRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        MyImage(NetworkImage(
            "https://avatars2.githubusercontent.com/u/20411648?s=460&v=4",
          ),
        ),
      ],
    );
  }
}

class MyImage extends StatefulWidget {
  MyImage(ImageProvider imageProvider){
    this.imageProvider=imageProvider;
  }
  ImageProvider? imageProvider;
  @override
  _MyImageState createState() => _MyImageState();
}

class _MyImageState extends State<MyImage> {
  ImageStream? _imageStream=null;
  ImageInfo? _imageInfo=null;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // We call _getImage here because createLocalImageConfiguration() needs to
    // be called again if the dependencies changed, in case the changes relate
    // to the DefaultAssetBundle, MediaQuery, etc, which that method uses.
    print("didChangeDependencies  _getImage");
    _getImage();
  }

  @override
  void didUpdateWidget(MyImage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.imageProvider != oldWidget.imageProvider) _getImage();
  }

  void _getImage() {
    print("_getImage");
    //ImageStream? oldImageStream = _imageStream;
    if(widget.imageProvider==null){
      print("imageProvider is null");
      return;
    }else{
      print("imageProvider not null");
    }
    _imageStream =(widget.imageProvider as ImageProvider).resolve(createLocalImageConfiguration(context));
    if (_imageStream==null) return;
    //if ((_imageStream as ImageStream).key != oldImageStream.key) {
      // If the keys are the same, then we got the same image back, and so we don't
      // need to update the listeners. If the key changed, though, we must make sure
      // to switch our listeners to the new image stream.
      final ImageStreamListener listener = ImageStreamListener(_updateImage);
      //oldImageStream.removeListener(listener);
      (_imageStream as ImageStream).addListener(listener);
    //}
  }

  void _updateImage(ImageInfo imageInfo, bool synchronousCall) {
    setState(() {
      // Trigger a build whenever the image changes.
      _imageInfo = imageInfo;
    });
  }

  @override
  void dispose() {
    if(_imageStream!=null)(_imageStream as ImageStream).removeListener(ImageStreamListener(_updateImage));
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if(_imageInfo==null){
      return Text("null");
    }
    else{
      return RawImage(
        image: (_imageInfo as ImageInfo).image, // this is a dart:ui Image object
        scale: (_imageInfo as ImageInfo ).scale ?? 1.0,
      );
    }
  }
}
